import React from 'react';
import PropTypes from 'prop-types';
import {Card, Button, Row, Col, Table} from 'antd';
import {TABLE, DATE_FORMAT, DATETIME_FORMAT, FILES_API} from '../constants';
import {conventEnumValueToString, formatDateTime, formatAmount} from '../utils';
import {partClaimCacuStatus, partClaimType, partClaimReasonStatus, currency} from '../Enum';
import {hasPermissions} from './utils';
import {PERMISSION} from './constants';
import DescriptionList from 'ant-design-pro/lib/DescriptionList';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import {abandonData} from './api';
import styles from './style.css';
import routes from './routes';
const {Description} = DescriptionList;

export class DetailPanel extends React.PureComponent {
    state = {
        loading: false,
    };
    componentDidMount() {
        this.props.init();
    }
    handleUpdateClick = () => {
        this.props.history.push(routes.update.format(this.props.id));
    }
    handleConfirmorClick = () => {
        this.props.history.push(routes.confirmor.format(this.props.id));
    }
    handleInvoiceClick = () => {
        this.props.history.push(routes.invoice.format(this.props.id));
    }
    abandonConfirm = () => {
        this.setState({loading: true});
        const rowVersion = this.props.detail.rowVersion;
        abandonData(this.props.detail.id, rowVersion)
            .then(res => {
                this.setState({loading: false});
                if(res.ok)
                    this.props.successReturn();
            });
    }
    render() {
        const detailData = this.props.detail || {};
        const {options, details, attachments = []} = detailData;
        const {isDealerUser} = this.props;
        const {formatMessage} = this.props.intl;
        const operations = [];
        if(hasPermissions(this.props.permissions, PERMISSION.update) && hasPermissions(options, PERMISSION.update))
            operations.push(<Button key="update" onClick={this.handleUpdateClick} size="small">{
                formatMessage({
                    id: 'detailPanel.btn.edit',
                    defaultMessage: '编辑'
                })
            }</Button>);
        if(hasPermissions(this.props.permissions, PERMISSION.confirmor) && hasPermissions(options, PERMISSION.confirmor))
            operations.push(<Button key="confirmor" onClick={this.handleConfirmorClick} size="small">{
                formatMessage({
                    id: 'detailPanel.btn.confirmor',
                    defaultMessage: '确认'
                })
            }</Button>);
        if(hasPermissions(this.props.permissions, PERMISSION.invoice) && hasPermissions(options, PERMISSION.invoice))
            operations.push(<Button key="invoice" onClick={this.handleInvoiceClick} size="small">{
                formatMessage({
                    id: 'detailPanel.btn.invoice',
                    defaultMessage: '发票确认'
                })
            }</Button>);
        if(hasPermissions(this.props.permissions, PERMISSION.abandon) && hasPermissions(options, PERMISSION.abandon))
            operations.push(
                <WrappedPopconfirm
                    id="abandon"
                    key="abandon"
                    title={formatMessage({
                        id: 'detailPanel.popconfirm.message',
                        defaultMessage: '是否继续?'
                    })}
                    onConfirm={this.abandonConfirm}>
                    <Button key="abandon" size="small">{
                        formatMessage({
                            id: 'detailPanel.btn.abandon',
                            defaultMessage: '作废'
                        })
                    }</Button>
                </WrappedPopconfirm>);
        const columns = [{
            title: formatMessage({
                id: 'detailPanel.column.reportCode',
                defaultMessage: '备件索赔报告编号'
            }),
            dataIndex: 'reportCode',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.claimCode',
                defaultMessage: '备件索赔单编号'
            }),
            dataIndex: 'claimCode',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.claimType',
                defaultMessage: '索赔类型'
            }),
            dataIndex: 'claimType',
            render: text => conventEnumValueToString(partClaimType, text)
        }, {
            title: formatMessage({
                id: 'detailPanel.column.currency',
                defaultMessage: '币种'
            }),
            dataIndex: 'currency',
            render: text => conventEnumValueToString(currency, text)
        }, {
            title: formatMessage({
                id: 'detailPanel.column.partCode',
                defaultMessage: '备件编号'
            }),
            dataIndex: 'partCode',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.partName',
                defaultMessage: '备件中文名称'
            }),
            dataIndex: 'partName',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.packingListCode',
                defaultMessage: '箱单号'
            }),
            dataIndex: 'packingListCode',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.partSaleOrderCode',
                defaultMessage: '备件销售订单编号'
            }),
            dataIndex: 'partSaleOrderCode',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.cacuQuantity',
                defaultMessage: '结算数量'
            }),
            dataIndex: 'cacuQuantity',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.price',
                defaultMessage: '索赔单价'
            }),
            dataIndex: 'price',
            render: text => formatAmount(text)
        }, {
            title: formatMessage({
                id: 'detailPanel.column.mgmtFee',
                defaultMessage: '管理费'
            }),
            dataIndex: 'mgmtFee',
            render: text => formatAmount(text)
        }, {
            title: formatMessage({
                id: 'detailPanel.column.claimReason',
                defaultMessage: '索赔原因'
            }),
            dataIndex: 'claimReason',
            render: text => conventEnumValueToString(partClaimReasonStatus, text)
        }, {
            title: formatMessage({
                id: 'detailPanel.column.claimFee',
                defaultMessage: '赔付金额'
            }),
            dataIndex: 'claimFee',
            render: text => formatAmount(text)
        }];
        if(!this.props.isDealerUser)
            columns.splice(12, 0, ...[
                {
                    title: formatMessage({
                        id: 'tablePanel.column.cacuFee',
                        defaultMessage: '结算金额'
                    }),
                    dataIndex: 'cacuFee',
                    render: text => formatAmount(text)
                },
            ]);
        return (
            <div className="detail">
                <Card loading={this.props.loading || this.state.loading}>
                    <DescriptionList size="large" title={<Row><Col span={12}>{
                        formatMessage({
                            id: 'detailPanel.card.title',
                            defaultMessage: '备件索赔结算信息'
                        })
                    }</Col>
                    <Col className={`col-align-right ${styles.detail}`} span={12}>{operations}</Col>
                    </Row>}>
                        <Description term={formatMessage({
                            id: 'detailPanel.data.code',
                            defaultMessage: '索赔结算编号',
                        })}>{this.props.detail.code}</Description>
                        { !isDealerUser && <Description term={formatMessage({
                            id: 'detailPanel.data.branchCode',
                            defaultMessage: '营销分公司编号',
                        })}>{this.props.detail.branchCode}</Description>}
                        { !isDealerUser && <Description term={formatMessage({
                            id: 'detailPanel.data.branchName',
                            defaultMessage: '营销分公司名称',
                        })}>{this.props.detail.branchName}</Description>}
                        { !isDealerUser && <Description term={formatMessage({
                            id: 'detailPanel.data.brandCode',
                            defaultMessage: '品牌编号',
                        })}>{this.props.detail.brandCode}</Description>}
                        { !isDealerUser && <Description term={formatMessage({
                            id: 'detailPanel.data.brandName',
                            defaultMessage: '品牌名称',
                        })}>{this.props.detail.brandName}</Description>}
                        { !isDealerUser && <Description term={formatMessage({
                            id: 'detailPanel.data.dealerCode',
                            defaultMessage: '总代编号',
                        })}>{this.props.detail.dealerCode}</Description>}
                        { !isDealerUser && <Description term={formatMessage({
                            id: 'detailPanel.data.dealerName',
                            defaultMessage: '总代名称',
                        })}>{this.props.detail.dealerName}</Description>}
                        <Description term={formatMessage({
                            id: 'detailPanel.data.status',
                            defaultMessage: '状态'
                        })}>{conventEnumValueToString(partClaimCacuStatus, this.props.detail.status)}</Description>
                        <Description term={formatMessage({
                            id: 'detailPanel.data.createTime',
                            defaultMessage: '申请日期',
                        })}>{formatDateTime(this.props.detail.createTime, DATE_FORMAT)}</Description>
                        { !isDealerUser && <Description term={formatMessage({
                            id: 'detailPanel.data.totalFee',
                            defaultMessage: '结算总金额',
                        })}>{formatAmount(this.props.detail.totalFee)}</Description>}
                        <Description term={formatMessage({
                            id: 'detailPanel.data.claimtTotalFee',
                            defaultMessage: '赔付总金额',
                        })}>{formatAmount(this.props.detail.claimtTotalFee)}</Description>
                        <Description term={formatMessage({
                            id: 'detailPanel.data.creatorName',
                            defaultMessage: '创建人姓名',
                        })}>{this.props.detail.creatorName}</Description>
                        <Description term={formatMessage({
                            id: 'detailPanel.data.modifierName',
                            defaultMessage: '修改人姓名',
                        })}>{this.props.detail.modifierName}</Description>
                        <Description term={formatMessage({
                            id: 'detailPanel.data.modifyTime',
                            defaultMessage: '修改时间',
                        })}>{formatDateTime(this.props.detail.modifyTime, DATETIME_FORMAT)}</Description>
                        <Description term={formatMessage({
                            id: 'detailPanel.data.confirmorName',
                            defaultMessage: '确认人姓名',
                        })}>{this.props.detail.confirmorName}</Description>
                        <Description term={formatMessage({
                            id: 'detailPanel.data.confirmTime',
                            defaultMessage: '确认时间',
                        })}>{formatDateTime(this.props.detail.confirmTime, DATETIME_FORMAT)}</Description>
                        <Description term={formatMessage({
                            id: 'detailPanel.data.invoiceConfirmorName',
                            defaultMessage: '发票确认人姓名',
                        })}>{this.props.detail.invoiceConfirmorName}</Description>
                        <Description term={formatMessage({
                            id: 'detailPanel.data.invoiceConfirmTime',
                            defaultMessage: '发票确认时间',
                        })}>{formatDateTime(this.props.detail.invoiceConfirmTime, DATETIME_FORMAT)}</Description>
                        <Description term={formatMessage({
                            id: 'detailPanel.data.payerName',
                            defaultMessage: '赔付人姓名',
                        })}>{this.props.detail.payerName}</Description>
                        <Description term={formatMessage({
                            id: 'detailPanel.data.payTime',
                            defaultMessage: '赔付时间',
                        })}>{formatDateTime(this.props.detail.payTime, DATETIME_FORMAT)}</Description>
                        <Description term={formatMessage({
                            id: 'detailPanel.data.abandonerName',
                            defaultMessage: '作废人姓名',
                        })}>{this.props.detail.abandonerName}</Description>
                        <Description term={formatMessage({
                            id: 'detailPanel.data.abandonTime',
                            defaultMessage: '作废时间',
                        })}>{formatDateTime(this.props.detail.abandonTime, DATETIME_FORMAT)}</Description>
                    </DescriptionList>
                </Card>
                <Card>
                    <DescriptionList title={formatMessage({
                        id: 'detailPanel.table.details',
                        defaultMessage: '备件索赔结算清单'
                    })}>
                        <Table
                            className="white-space-nowrap"
                            columns={columns}
                            rowKey="id"
                            pagination={false}
                            dataSource={details}
                            {...TABLE} />
                    </DescriptionList>
                </Card>
                <Card>
                    <DescriptionList title={formatMessage({
                        id: 'detailPanel.card.attachment',
                        defaultMessage: '附件清单'
                    })} size="large">
                        {attachments.map(item => (<Description key={item.fileId}>
                            <a icon="download" download href={`${FILES_API.files}/${item.fileId}`} size="small">
                                {item.fileName}</a></Description>))}
                    </DescriptionList>
                </Card>
                <div className="page-toolbar">
                    <Button
                        type="primary"
                        disabled={this.props.loading || this.state.loading}
                        onClick={this.props.onCancel}>{formatMessage({
                            id: 'detailPanel.btn.return',
                            defaultMessage: '返回'
                        })}</Button>
                </div>
            </div>
        );
    }
}

DetailPanel.propTypes = {
    detail: PropTypes.object.isRequired,
    id: PropTypes.string.isRequired,
    init: PropTypes.func.isRequired,
    loading: PropTypes.bool.isRequired,
    permissions: PropTypes.array.isRequired,
    onCancel: PropTypes.func.isRequired,
    history: PropTypes.object,
    intl: PropTypes.object,
    isDealerUser: PropTypes.bool,
    successReturn: PropTypes.func,
};

import {connect} from 'react-redux';
import {getDetail, tableSearch} from './actions';
import {injectIntl} from './intl';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const getDetailData = selectorFactory(['page', 'domainData', 'detail', 'data']);
const mapStateToProps = (state, props) => ({
    id: props.id,
    loading: state.getIn(['page', 'domainData', 'detail', 'isFetching']),
    permissions: getPermissions(state),
    detail: getDetailData(state),
    isDealerUser: state.getIn(['page', 'domainData', 'init', 'isDealerUser']),
});
const mapDispatchToProps = (dispatch, props) => ({
    init: () => dispatch(getDetail(props.id)),
    onCancel: () => {
        props.history.push(routes.query.url());
    },
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(DetailPanel));
